package com.ke.shiro;

import com.ke.dao.UserRepository;
import com.ke.pojo.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author bochen
 */
@Component
public class MyRealm extends AuthorizingRealm {
    private UserRepository userRepository;
    @Autowired
    public void setUserRepository(UserRepository userRepository){
        this.userRepository=userRepository;
    }
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.通过用户名查找数据库密码
        String principal= (String) authenticationToken.getPrincipal();
        //2.获取用户
        User user=userRepository.findByUsername(principal);
        //3.加盐:ke
        String salt="ke";
        if (user!=null){
            return new SimpleAuthenticationInfo(principal,user.getPassword(), ByteSource.Util.bytes(salt),this.getName());
        }
        return null;
    }
}